package com.ease.framework.gef.ui {
   import flash.events.Event;
   import flash.events.EventDispatcher;
   
   import mx.collections.ArrayCollection;

   public class SelectionManager extends EventDispatcher {
      private var _items:Array = new Array();
      private var currentlySelecteds:ArrayCollection = new ArrayCollection();

      public function setSelected(obj:ISelection):void {
         for each (var selObj:ISelection in currentlySelecteds) {
            selObj.deselect();
         }
         currentlySelecteds = new ArrayCollection();
         addSelected(obj);
      }

      public function addSelected(obj:ISelection):void {
         if (currentlySelecteds.contains(obj))
            return;
         currentlySelecteds.addItem(obj);
         obj.select();
         dispatchEvent(new Event("selectionChange"));
      }

      public function removeSelected(obj:ISelection):void {
         obj.deselect();
         if (currentlySelecteds.contains(obj)) {
            currentlySelecteds.removeItemAt(currentlySelecteds.getItemIndex(obj));
         }
         dispatchEvent(new Event("selectionChange"));
      }

      public function clearSelected():void {
         for each (var obj:ISelection in currentlySelecteds) {
            obj.deselect();
         }
         currentlySelecteds = new ArrayCollection();
         dispatchEvent(new Event("selectionChange"));
      }

      [Bindable("selectionChange")]
      public function get numSelected():int {
         return currentlySelecteds.length;
      }

      [Bindable("selectionChange")]
      public function get selecteds():Array {
         return currentlySelecteds.toArray();
      }

      public function addSelectable(obj:ISelection):void {
         var ind:int = _items.indexOf(obj);
         if (ind != -1) {
            return;
         }
         _items.push(obj);
      }

      public function removeSelectable(obj:ISelection):void {
         var ind:int = _items.indexOf(obj);
         if (ind == -1) {
            return;
         }
         _items.splice(ind, 1);
      }
   }
}